
/**
 * 成功返回
 * @param {*} ctx 
 * @param {*} data 数据
 * @param {*} msg 描述
 */
 const resSuccess = async function(ctx,msg='操作成功',data=[]){
    ctx.response.body = {
        code: 200,
        data: data,
        msg: msg
    };
}

/**
 * 失败返回
 * @param {*} ctx 
 * @param {*} msg 描述
 * @param {*} code 状态码
 */
 const resError = async function(ctx,msg='操作异常',code=-200){
    ctx.response.body = {
        code: code,
        msg: msg
    };
}

/**
 * 获取UUID
 * @returns uuid
 */
const getUUID = async function(){
    return `${process.env.pm_id}-${new Date().getTime()}-${Math.round(Math.random()*9)}${Math.round(Math.random()*9)}${Math.round(Math.random()*9)}${Math.round(Math.random()*9)}`;
}

/**
 * 获取请求IP
 * @param {*} req 
 * @returns 
 */
async function getClientIP(req) {
    let ip = req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
        req.ip ||
        req.connection.remoteAddress || // 判断 connection 的远程 IP
        req.socket.remoteAddress || // 判断后端的 socket 的 IP
        req.connection.socket.remoteAddress || ''
    if (ip) {
        ip = ip.replace('::ffff:', '')
    }
    return ip;
}

module.exports = {
    getClientIP:getClientIP,
    resSuccess:resSuccess,
    resError:resError,
    getUUID:getUUID
}